/**
 * 抖音关注：程序员三丙
 * 知识星球：https://t.zsxq.com/j9b21
 */
package sanbing.example.dylike.application.rpc;

import com.google.common.util.concurrent.ListenableFuture;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import sanbing.example.dylike.infrastructure.queue.QueueMsg;
import sanbing.example.dylike.infrastructure.queue.provider.QueueFactory;
import sanbing.example.dylike.infrastructure.queue.rpc.QueueRequestTemplate;
import sanbing.example.dylike.util.MessagesStats;
import sanbing.example.dylike.util.StatsFactory;

import java.util.UUID;


@Slf4j
@Service
public class RpcRequestQueueService {

    @Resource
    QueueFactory queueFactory;
    @Resource
    StatsFactory statsFactory;

    protected MessagesStats rpcStats;
    protected QueueRequestTemplate seckillRpcRequestTemplate;

    @PostConstruct
    public void init() {
        this.rpcStats = statsFactory.createMessagesStats("rpc.producer");
        seckillRpcRequestTemplate = queueFactory.createSeckillRpcRequestTemplate();
        seckillRpcRequestTemplate.setMessagesStats(rpcStats);
        seckillRpcRequestTemplate.init();
    }

    @PreDestroy
    public void destroy() {
        if (seckillRpcRequestTemplate != null) {
            seckillRpcRequestTemplate.stop();
        }
    }

    @SneakyThrows
    public ListenableFuture<QueueMsg> doSeckill(RpcRequest rpcRequest) {
       return seckillRpcRequestTemplate.send(new QueueMsg(UUID.randomUUID(), rpcRequest.toBytes()));
    }
}